package com.dennisstepp.database;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

	private static final String DATABASE_PATH = "/data/data/com.dennisstepp/databases";
	private static final String DATABASE_NAME = "collec.sqlite";
	private static final int DATABASE_VERSION = 1;
	private SQLiteDatabase myDatabase;
	private final Context myContext;

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.myContext = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	/**
	 * Creats an empty database on the system and rewrites it with pop. db
	 */
	public void createDatabase() throws IOException {
		createDB();
	}

	private void createDB() {
		boolean dbExist = DBExists();

		if (!dbExist) {
			this.getWritableDatabase();
			copyDBFromResource();
		}
	}

	private void copyDBFromResource() {

		InputStream inputStream = null;
		OutputStream outStream = null;
		String dbFilePath = DATABASE_PATH + DATABASE_NAME;

		try {
			inputStream = myContext.getAssets().open(DATABASE_NAME);

			outStream = new FileOutputStream(dbFilePath);

			byte[] buffer = new byte[1024];
			int length;
			while ((length = inputStream.read(buffer)) > 0) {
				outStream.write(buffer, 0, length);
			}
			outStream.flush();
			outStream.close();
			inputStream.close();
		} catch (IOException e) {
			throw new Error("Problem COPYING database from resource file.");
		}
	}

	public void openDatabase() throws SQLException {
		String myPath = DATABASE_PATH + DATABASE_NAME;
		myDatabase = SQLiteDatabase.openDatabase(myPath, null,
				SQLiteDatabase.OPEN_READWRITE);
	}

	private boolean DBExists() {
		SQLiteDatabase db = null;

		try {
			String databasePath = DATABASE_PATH + DATABASE_NAME;
			db = SQLiteDatabase.openDatabase(databasePath, null,
					SQLiteDatabase.OPEN_READWRITE);
			db.setLocale(Locale.getDefault());
			db.setLockingEnabled(true);
			db.setVersion(1);
		} catch (SQLiteException e) {
			Log.e("SqlHelper", "database not found");
		}
		if (db != null) {
			db.close();
		}
		return db != null ? true : false;
	}

	@Override
	public synchronized void close() {
		if (myDatabase != null) {
			myDatabase.close();
		}
		super.close();
	}
}